using WebapiTemplate.Application.Common;
using WebapiTemplate.Domain.Base;
using System;
using Microsoft.EntityFrameworkCore;

namespace WebapiTemplate.Infrastructure.Persistence
{
    public class EfRepository<T> : IRepository<T> where T:BaseEntity
    {
        private readonly WebapiDbcontext _db;
        public DbSet<T> _table;
        

        public EfRepository(WebapiDbcontext db)//添加数据库的构造函数且参数不能为null，只能这样了
        {
            _db = db;
            _table = _db.Set<T>();
        }
    
        //新增
        public void Add(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            //   entity.CreatedBy = 0;
            //   entity.UpdatedBy = 0;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;
            entity.Remarks = "没有评论";

            _table.Add(entity);
            _db.SaveChanges();
        }

        public async Task SaveAsync(T entity)
        {
            //AuditActionFilter类传来的表数据不存在则抛出异常

            entity.IsActived = true;
            entity.IsDeleted = false;
            // entity.CreatedBy = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;

            await _db.AddAsync(entity);
            await _db.SaveChangesAsync();
        }
    }
}